/**
 * Flickr Class - Created by FlashFrameLess Team OCT/2008
 *
 * @author		FabioTNT / FlashFrameLessTeam - http://www.flashframeless.com/
 * @version		1.0
 */

package com.flashframeless.webapis.flickr {
	
	import flash.display.MovieClip;
	import flash.events.*;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	public class Flickr extends EventDispatcher {
		
		private var _apiKEY			: String;
		private var _apiPOOL		: String;
		private var _loader			: URLLoader;
		private var _xml			: XML;
		private var i				: uint;	
		private var _defaultUser	: String;
		private var _arrPhotos		: Array = new Array();
		
		public function Flickr() {
			
			//
			
		}
		
		public function searchImagesByUser( qtd:uint = 100, user:String = '', tags:String = '' ):void {
			
			if ( user == '' ) {
				
				user = _defaultUser;
				
			}
			
			var method	: String = 'flickr.photos.search';
			var url		: String = _apiPOOL + "?method=" + method + "&api_key=" + _apiKEY + "&user_id=" + user + "&tags=" + tags + "&tag_mode=all" + "&per_page=" + qtd;			
			
			search( url );
			
		}
		
		
		
		private function search( url:String ):void {
			
			_loader = new URLLoader();
			
			_loader.addEventListener( Event.COMPLETE, searchComplete );
			_loader.load( new URLRequest( url ) );
			
		}
		
		private function searchComplete( evt:Event ):void {
			
			//Extract data
			_xml = new XML( evt.target.data );
			ParseData( _xml );
			
		}
		
		private function ParseData( data:XML ):void {
			
			_arrPhotos = [];
			
			for ( i = 0; i < _xml.photos.photo.length(); i++ ) {
				
				_arrPhotos.push( {
					
					id:_xml.photos.photo[i].@id,
					owner:_xml.photos.photo[i].@owner,
					secret:_xml.photos.photo[i].@secret,
					server:_xml.photos.photo[i].@server,
					farm:_xml.photos.photo[i].@farm,
					title:_xml.photos.photo[i].@title,
					ispublic:_xml.photos.photo[i].@ispublic,
					isfriend:_xml.photos.photo[i].@isfriend,
					isfamily:_xml.photos.photo[i].@isfamily,
					url:"http://farm"+_xml.photos.photo[i].@farm+".static.flickr.com/"+_xml.photos.photo[i].@server+"/"+_xml.photos.photo[i].@id+"_"+_xml.photos.photo[i].@secret					
					
				} );
				
			}
			
			dispatchEvent( new Event( Event.COMPLETE ) );
			
		}
		
		
		
		public function get arrPhotos():Array {
			
			return _arrPhotos;
			
		}
		
		public function set key( apiKey:String ):void {
			
			_apiKEY = apiKey;
			
		}
		
		public function set pool( apiPool:String ):void {
			
			_apiPOOL = apiPool;
			
		}
		
		public function set defaultUser( user:String ) {
			
			_defaultUser = user;
			
		}
		
	}
}